<?php
/**
 * 计算订单取消费用，是根据票数退款哦~
 *
 * @author GuangPeng Chen
 * @param Int $tid      门票ID
 * @param Int $price    价格（单位分）
 * @param string $beginTime     订单游玩时间
 * @return array|bool|int       成功返回退票手续费，金额分
 */
function count_cost_fee( $tid, $price, $beginTime)
{
    $play_date = strtotime( $beginTime . ' 00:00:00');
    $today     = strtotime(date('Y-m-d 00:00:00'));
    $day_diff  = ($play_date - $today) / 86400;//距离游玩时间的天数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额
    //reb_type
    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket"
        . " WHERE id=$tid LIMIT 1";
    $GLOBALS['le']->query($sql);
    $total_fee    = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row    = $GLOBALS['le']->fetch_assoc()) {
        if ($row['cancel_cost']) {
//            if (!$row['cancel_cost']) continue;
            $cancel_cost = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                //按百分比收取手续费
                $total_fee += ($row['reb'] * $price) / 100;
            }
        }
    }
    //阶梯扣费
    /*    `cancel_cost` varchar(2000) NOT NULL,
    /*取消费用 二维数组 array(array('c_type'=>类型 0 固定金额 1 百分比,
    'c_days'=>游玩前分钟（乘以100的倍数）,
    'c_cost'=>费用值（百分比的值有问题，是乘以100后再乘以100的值）))*/
    if (isset($cancel_cost) && !empty($cancel_cost)) {
        //取消费用一维数组 array('提前天数'=>'百分比')
        $play_date = strtotime($beginTime .' '. date('H:i:s'));//游玩时间（分钟）
        $today     = $_SERVER['REQUEST_TIME'];//当前时间（分钟）
        $minute_diff  = ($play_date - $today) / 60 ;//距离游玩时间的分钟数
        $cancel_cost_arr = json_decode($cancel_cost, true);
        $fee_cfg = array();
        foreach ($cancel_cost_arr as $list) {
            if ($list['c_type']==0) {
                $fee_cfg[$list['c_days']/100] = $list['c_cost'];
            } else {
                $fee_cfg[$list['c_days']/100] = $price * ($list['c_cost'] / 100 / 100);
            }
        }
//        $day_arr         = array_keys($cancel_cost_arr);
        $minute_arr         = array_keys($fee_cfg);
//        sort($minute_arr);
        $min_minute         = min($minute_arr);
        $max_minute         = max($minute_arr);
//        print_r($minute_arr);
//        print_r($cancel_cost_arr);
//        print_r($fee_cfg);
//        echo 'price',$price,PHP_EOL,'playday=',$beginTime,PHP_EOL,
//        ';minDiff=',$minute_diff,PHP_EOL,
//        '$min_minute=',$min_minute,PHP_EOL,';$max_minute=', $max_minute,
//        ';$today=',$today,PHP_EOL,';$play_date=',$play_date,PHP_EOL;
        if ( $minute_diff < 10 ) {//允许10分钟误差
            $fee = $fee_cfg[$min_minute];
        }
        elseif ($minute_diff <= $min_minute) {
            $fee = $fee_cfg[$min_minute];
        }
        elseif ($minute_diff >= $max_minute) {
            $fee = 0;
        }
        else {
            //345600 2419200 4492800
            //2419100
            foreach ($minute_arr as $key=>$val) {
                if ($minute_diff >= $val && $minute_diff <= $minute_arr[$key+1]) {
                    $_k  = (int)$minute_arr[$key+1]['c_days']/100;
                    $fee = $fee_cfg[$_k];
                    break;
                }
            }
        }
        $total_fee += $fee;
    }
    return $total_fee;
}

function count_cost_fee_dev( $tid, $price, $beginTime)
{
    $play_date    = strtotime( $beginTime . ' 00:00:00');
    $now_timestamp     = $_SERVER['REQUEST_TIME'];
    $minute_diff  = $play_date - $now_timestamp;//距离游玩时间的分钟数
    //取消费用,cancel_cost,reb=>手续费,reb_type=>手续费类型0%，1固定金额
    $sql = "SELECT id,cancel_cost,reb,reb_type,apply_did FROM uu_jq_ticket"
        . " WHERE id=$tid LIMIT 1";
    $GLOBALS['le']->query($sql);
    $total_fee    = 0;//取消费用，考虑到后期有可能订单里面的票取消费用计算方式不一致
    while($row    = $GLOBALS['le']->fetch_assoc()) {
        //in_array($row['apply_did'], $use_cancel_cost) &&
        if ($row['cancel_cost']) {
            $cancel_cost = $row['cancel_cost'];
        }
        elseif ($row['reb']>0) {
            if ($row['reb_type']==1) {
                $total_fee += $row['reb'];
            }
            else {
                //按百分比收取手续费
                $total_fee += ($row['reb'] * $price) / 100;
            }
        }
    }
    //阶梯扣费
//    print_r($cancel_cost);
//    `cancel_cost` varchar(2000) NOT NULL, /*取消费用
//    二维数组 array(array('c_type'=>类型 0 固定金额 1 百分比,'c_days'=>游玩前分钟,'c_cost'=>费用值))*/
    if (isset($cancel_cost) && !empty($cancel_cost)) {
        //取消费用一维数组 array('提前天数'=>'百分比')
        $conf_arr = json_decode($cancel_cost, true);
        print_r($conf_arr);
        foreach ($conf_arr as $key=>$cancel) {
            $cancel_cost_arr[$cancel['c_days']*60] = $key;
        }
        $minute_arr         = array_keys($cancel_cost_arr);
        $min_minute         = min($minute_arr);
        $max_minute         = max($minute_arr);
        $fee = 0;
        if ($minute_diff <= $min_minute) {
            $c_type = $conf_arr[$cancel_cost_arr[$min_minute]]['c_type'];
            if ($c_type==1) {
                $fee = $price * $conf_arr[$cancel_cost_arr[$min_minute]]['c_cost'] / 100;
            } else {
                $fee = $conf_arr[$cancel_cost_arr[$min_minute]]['c_cost'];//单位为分
            }
        }
        elseif ($minute_diff >= $max_minute) {
        }
        else {
            $keys = array_keys($minute_arr);
            print_r($keys);
            foreach ($minute_arr as $minute=>$conf_key) {
                $position = array_search($minute, $keys);
                if (isset($keys[$position + 1])) {
                    $keyAfterTwoVal = $keys[$position + 1];
                }

                if ($minute_diff >= $minute && $minute_diff <= $minute_arr[$keyAfterTwoVal]) {
                    $conf_key = $cancel_cost_arr[$minute_arr[$keyAfterTwoVal]];
                    echo 'conf-key=' . $conf_key,PHP_EOL;
                    $c_type = $conf_arr[$conf_key]['c_type'];
                    if ($c_type==1) {
                        $fee = $price * $conf_arr[$conf_key]['c_cost'] / 100;
                    } else {
                        $fee = $conf_arr[$conf_key]['c_cost'];//单位为分
                    }
                    break;
                }
            }
        }
        $total_fee += $fee  ;
    }
    return $total_fee;
}
function LogRefund($txt,$file='/var/www/html/new/d/logs/refund_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

function Response( $msg, $status = "fail") {
    $json = '{"status":"'.$status.'", "msg":"'.$msg.'"}';
    exit($json);
}